package models

import (
	"database/sql"
	"log"
	"time"

	_ "github.com/denisenkom/go-mssqldb"
)

type Data struct {
	PerCode    string    //个人编号
	AccName    string    //姓名
	CertCode   string    //证件号码
	PerSex     string    //性别
	AccStatus  string    //状态
	AccClsCode string    //账户身份 教师等
	PostDate   time.Time //配卡日期
	LostDate   time.Time //启用日期
	DepName    string    //部门/班级
	CardNO     string    // 物理卡号
}

func GetCardData(dsn string) ([]Data, error) {
	db, err := sql.Open("mssql", dsn)
	if err != nil {
		return nil, err
	}
	defer db.Close()

	query := "SELECT t1.PerCode, t1.AccName, t1.CertCode, t1.PerSex, t1.AccStatus, t1.AccClsCode, t1.PostDate, t1.LostDate, t2.DepName ,t1.CardNO FROM ac_dict_Accounts t1, ac_dict_AccDep t2 WHERE t1.DepCode = t2.DepCode and t1.CertCode != ''"
	rows, err := db.Query(query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var results []Data
	for rows.Next() {
		var r Data
		err := rows.Scan(&r.PerCode, &r.AccName, &r.CertCode, &r.PerSex, &r.AccStatus, &r.AccClsCode, &r.PostDate, &r.LostDate, &r.DepName, &r.CardNO)
		if err != nil {
			log.Fatal(err)
		}
		results = append(results, r)
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}

	// 打印结果列表
	for _, r := range results {
		lg.Debugf("数据 r.PerCode: %s, r.AccName: %s, r.CertCode: %s, r.PerSex: %s, r.AccStatus: %s, r.AccClsCode: %s, r.PostDate: %s, r.LostDate: %s, r.DepName: %s, r.CardNO: %s", r.PerCode, r.AccName, r.CertCode, r.PerSex, r.AccStatus, r.AccClsCode, r.PostDate, r.LostDate, r.DepName, r.CardNO)
	}
	return results, nil
}
